<template>
<div class="AdministrativeList">
    <el-row class="line">
        <el-col :span="6">
            <!-- :current-node-key="data.administrativeCode" -->
            <el-card>
                <el-tree highlight-current @node-click="handleNodeClick" :current-node-key="data.productTypeCode" :data="data" ref="tagtree" :props="defaultProps" :load="loadNode" lazy>
                </el-tree>
            </el-card>
        </el-col>
        <el-col :span="18">
            <el-card>
                <el-form :inline="false" ref="form" :rules="rules" :model="areaModel" label-width="80px" class="demo-form-inline">
                    <el-form-item label="分类编号" prop="productTypeCode">
                        <el-input v-model="areaModel.productTypeCode" minlength="6" maxlength="12" show-word-limit placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item label="分类名称" prop="productTypeName">
                        <el-input v-model="areaModel.productTypeName" minlength="2" maxlength="20" show-word-limit placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item label="单价(元)" prop="price">
                        <el-input v-model="areaModel.price" minlength="2" maxlength="20" show-word-limit placeholder="请输入单价"></el-input>
                    </el-form-item>

                    <el-form-item label="单位" prop="unit">
                     <el-select style="width:100%"  @focus="propertyValue"  v-model="areaModel.unit"  placeholder="请选择">
                            <el-option
                            v-for="item in landOutputUnit"
                            :key="item.value"
                            :label="item.label"
                            :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上级分类" prop="productTypeParentCode">
                        <el-input v-model="areaModel.productTypeHighName" minlength="2" maxlength="20" show-word-limit :disabled="true"></el-input>
                        <el-input v-model="areaModel.productTypeParentCode" minlength="2" maxlength="20" show-word-limit v-if="false"></el-input>
                    </el-form-item>

                    <el-form-item label="分类等级" prop="productTypeLevel">
                        <el-select :disabled="true" v-model="areaModel.productTypeLevel" style="width:100%">
                            <el-option label="一级分类" :value="1"></el-option>
                            <el-option label="二级分类" :value="2"></el-option>
                            <el-option label="三级分类" :value="3"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button style="float:left" type="primary" :disabled="disableButton01" @click="showOther('form')">新增子分类</el-button>
                        <el-button style="float:left" type="primary" @click="edit('form')">保存</el-button>
                        <el-button style="float:left" type="info" @click="del('form')">删除</el-button>
                    </el-form-item>

                </el-form>

            </el-card>
        </el-col>
    </el-row>

</div>
</template>

<script>
import axios from "@/api/request.js";
import {
    convertKey
} from "@/library";
import {
    checkNumber
} from "@/library/regexp.js";
export default {
    name: "AdministrativeList",
    data() {
        return {
            nodeClick: {},
            administrativeHigh: "",
            disableButton01: false,
            modify: 0,
            data: [{
                id: 1,
                label: '佛山市',
                children: [{
                    id: 2,
                    label: '南海区',
                    children: [{
                        id: 3,
                        label: '里水镇2'
                    }, {
                        id: 4,
                        label: '桂花街道2'
                    }]
                }]
            }],
            defaultProps: {
                children: "children",
                //label: "label",
                label: 'productTypeName',
                id: 'productTypeCode',
                parentId: 'productTypeParentCode',
                isLeaf: false
            },
            isAddOrigan: false,
            addOrganizationForm: {},
            areaModel: {
                productTypeCode: "",
                productTypeName: "",
                unit: "",
                price: ""
            },
            tableData2: [],

            OrganizationTree: [],
            search: {
                planName: "",
                planStatus: [{
                        value: 0,
                        label: "全部",
                    },
                    {
                        value: 1,
                        label: "未发布",
                    },
                    {
                        value: 2,
                        label: "已发布",
                    },
                    {
                        value: 3,
                        label: "已撤回",
                    },
                    {
                        value: 4,
                        label: "已启用",
                    },
                    {
                        value: 5,
                        label: "已停用",
                    },
                ],
                value: "",
            },
            params: {
                pageNumber: 1,
                pageSize: 10,
            },
            landOutputUnit:{},
            paging: {},
            tableData: [],
            rules: {
                price: [{
                    required: true,
                    validator: checkNumber('单价必须是数字'),
                    trigger: 'blur'
                }],
                productTypeCode: [{
                        required: true,
                        message: '行政分类编号不能为空',
                        trigger: 'blur'
                    }
                ],
                productTypeName: [{
                        required: true,
                        message: '分类名称不能为空',
                        trigger: 'blur'
                    }
                ]
            }
        };
    },
    computed: {
        treeItem() {
            let administrative
            if (localStorage.getItem('treeItem')) {
                administrative = JSON.parse(localStorage.getItem('treeItem'))
            } else {
                administrative = this.tableData
            }
            return administrative
        }
    },
    created() {
        this.getAdministrativeList();
    },
    mounted() {
        //this.treeLoad();
    },
    methods: {
        propertyValue() {
            this.$axios
                .get("/baseinfo/baseInfo/propertyValue/select", {
                    params: {
                        ptCode: "P01",
                    },
                })
                .then((res) => {
                    this.landOutputUnit = convertKey(res.data, {
                        pvCode: "value",
                        propertyValue: "label",
                    });
                });
        },
        loadNode(node, resolve) { // 加载 树数据   
            let that = this;
            this.nodeClick = node;
            if (node.level === 0) {
                that.loadtreeData(resolve);
            }

            if (node.level >= 1) {
                this.getChildByList(node.data.productTypeCode, resolve);
                return resolve([]); // 加上这个，防止在该节点没有子节点时一直转圈的问题发生。
            }
        },
        loadtreeData() {
            axios.get(
                `baseinfo/api/v1.0/fishing/landTypep/productType/getByPid`, {
                    params: {
                        pid: 0
                    }
                }).then((res) => {
                let data = res.data;
                this.data = res.data;

                // 前者item.参数名称为 prop中的规定的属性名称
                data.forEach(item => {
                    item.productTypeCode = item.productTypeCode;
                    item.productTypeParentCode = item.productTypeParentCode;
                    item.productTypeName = item.productTypeName;
                    item.isLeaf = true;
                });
                resolve(data)
            });

        },

        getChildByList(pid, resolve) { // 获取子节点请求
            let params = {
                pid: pid
            };
            axios.get(
                `baseinfo/api/v1.0/fishing/landTypep/productType/getByPid`, {
                    params: params
                }).then((res) => {
                let data = res.data;
                // 前者item.参数名称为 prop中的规定的属性名称
                data.forEach(item => {
                    item.productTypeCode = item.productTypeCode;
                    item.productTypeParentCode = item.productTypeParentCode;
                    item.productTypeName = item.productTypeName;
                    item.isLeaf = true;
                });
                resolve(data)

            });
        },
        treeLoad() {
            let url = '/tree.json'
            fetch(url)
                .then(response => response.json())
                .then(res => {
                    this.data = res.data.treeItem;
                    this.data = convertKey(this.data, {
                        administrativeName: "label",
                        administrativeCode: "id",
                    });
                })

        },
        handleNodeClick(data, e) {
            console.log(data);
            console.log(e.parent.data);

            //this.nodeClick=e;
            this.areaModel.id = data.id;
            this.areaModel.productTypeCode = data.productTypeCode;
            this.areaModel.productTypeName = data.productTypeName;
            this.areaModel.productTypeParentCode = data.productTypeParentCode;

            this.areaModel.productTypeHighName = e.parent.data.productTypeName;
            this.areaModel.productTypeLevel = data.productTypeLevel;

            this.areaModel.price = data.price;
            this.areaModel.unit = data.unit;
            //是否能创建子分类 3、4可以 5不可以
            if (this.areaModel.productTypeLevel == 3) {
                this.disableButton01 = true;
            } else {
                this.disableButton01 = false;
            }

            //修改状态
            this.modify = 1;
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },

        statusChange(item) {
            console.log(item);
        },
        planStatusCn(index) {
            var planStatus = {
                1: "未发布",
                2: "已发布",
                3: "已撤回",
                4: "已启用",
                5: "已停用",
            };

            return planStatus[index];
        },
        load(tree, treeNode, resolve) {
            setTimeout(() => {
                resolve([{
                    id: 31,
                    date: '2016-05-01',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1519 弄'
                }, {
                    id: 32,
                    date: '2016-05-01',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1519 弄'
                }])
            }, 1000)
        },
        onSearch() {},
        handleSizeChange(pageSize) {
            this.params.pageSize = pageSize;
            this.getAdministrativeList(this.params.pageNumber, this.params.pageSize);
        },
        currentchange(pageNumber) {
            this.params.pageNumber = pageNumber;
            this.getAdministrativeList(this.params.pageNumber, this.params.pageSize);
        },
        getAdministrativeList(pageNumber = 1, pageSize = 10) {
            this.$common.getAdministrativeList(pageNumber, pageSize).then((res) => {
                this.tableData = res.data.treeItem;
                localStorage.setItem('treeItem', JSON.stringify(this.tableData))

            });
        },
        showOther() {
            //新增状态 
            this.modify = 0;
            this.areaModel.productTypeParentCode = this.areaModel.productTypeCode;
            this.areaModel.productTypeHighName = this.areaModel.productTypeName;
            this.areaModel.productTypeLevel = this.areaModel.productTypeLevel + 1;
            this.areaModel.productTypeCode = "";
            this.areaModel.productTypeName = "";
        },
        edit(formName) {

            this.$refs[formName].validate((valid) => {
                if (valid) {

                    let jsonData = {
                        productTypeCode: this.areaModel.productTypeCode,
                        productTypeName: this.areaModel.productTypeName,
                        productTypeParentCode: this.areaModel.productTypeParentCode,
                        productTypeLevel: this.areaModel.productTypeLevel,
                        price: this.areaModel.price,
                        unit: this.areaModel.unit,
                    }
                    //新增或修改 新节点  
                    if (this.modify == 0) {
                        //新增
                        axios.post(
                            `baseinfo/api/v1.0/fishing/landTypep/productType/insert`, {
                                params: jsonData
                            }).then((response) => {
                            console.log(response)
                            this.$message.success(response.errorMsg);
                            this.areaModel.productTypeCode = "";
                            this.areaModel.productTypeName = "";
                            //局部更新
                            this.refreshNodeBy(this.nodeClick.parent);
                        });
                    } else {

                        jsonData.id = this.areaModel.id;
                        //修改
                        axios.post(
                            `baseinfo/api/v1.0/fishing/landTypep/productType/update`, {
                                params: jsonData
                            }).then((response) => {
                            console.log(response)
                            //该行政编码已经存在
                            if (response.errorCode == '00000') {
                                this.$message.success("操作完成");
                            } else {
                                this.$message.success("该行政编码已经存在");
                            }

                            //局部更新
                            this.refreshNodeBy(this.nodeClick.parent);
                        });
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });

        },
        refreshNodeBy(id) {
            let node = this.$refs.tagtree.getNode(id); // 通过节点id找到对应树节点对象
            //
            node.loaded = false;
            node.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
        },
        del() {
            //选中后，删除节点
            this.$confirm('是否删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                axios.get(
                    `baseinfo/api/v1.0/fishing/landTypep/productType/delete`, {
                        params: {
                            id: this.areaModel.id
                        }
                    }).then((response) => {
                    console.log(response)
                    if (response.errorCode === '00000') {
                        this.$message.success('删除成功');
                        this.areaModel.productTypeCode = "";
                        this.areaModel.productTypeName = "";
                        //局部更新
                        this.refreshNodeBy(this.nodeClick.parent);
                    } else {
                        this.$message.error(response.errorMsg);
                    }

                });
            }).catch(() => {});

        },

    },
};
</script>

<style lang="scss">
.AdministrativeList {
    .form {
        padding: 15px 10px;
    }

    .el-card {
        width: 98%;
        margin: 0 auto;

        .bottom {
            display: flex;
            justify-content: flex-end;
            margin-top: 15px;
        }
    }

    .line {
        margin-top: 15px;
    }
}
</style>
